import json
import os
import random
import re
import shutil
import urllib

import cv2
import requests
from fitz import fitz
from pyzbar import pyzbar
from flask import Flask, request, jsonify


import pandas as pd
from paddleocr import PaddleOCR

app = Flask(__name__)
app.config['DEBUG'] = True


@app.route('/', methods=["GET"])  # GET 和 POST 都可以
def get_data():
    # 假设有如下 URL
    # http://10.8.54.48:5000/index?name=john&age=20

    # 可以通过 request 的 args 属性来获取参数
    url = request.args.get("pdf_url")
    print(url)
    folder_PDF_path = r'PDF-OCR\PDF'
    # folder_PIC_path = r'PDF-OCR\PIC'
    # listpicpath = set()
    # listpdfpath = set()
    final_result=[]
    # 下载pdf实现方法
    def get_pdf_by_url(folder_path, url):
        if not os.path.exists(folder_path):
            print("Selected folder not exist, try to create it.")
            os.makedirs(folder_path)

        print("Try downloading PDF file: {}".format(url))
        filename = url.split('/')[-1]
        filepath = folder_path + '/' + filename
        if os.path.exists(filepath):
            print("PDF File have already exist. skip")
        else:
            try:
                urllib.request.urlretrieve(url, filename=filepath)
            except Exception as e:
                print("Error occurred when downloading file, error message:")
                print(e)

    # 下载图片实现方法
    def get_pic_by_url(folder_path, lists):
        if not os.path.exists(folder_path):
            print("Selected folder not exist, try to create it.")
            os.makedirs(folder_path)
        for url in lists:
            print("Try downloading PIC file: {}".format(url))
            filename = url.split('/')[-1]
            filepath = folder_path + '/' + filename
            if os.path.exists(filepath):
                print("PIC File have already exist. skip")
            else:
                try:
                    urllib.request.urlretrieve(url, filename=filepath)
                except Exception as e:
                    print("Error occurred when downloading file, error message:")
                    print(e)

    #
    get_pdf_by_url(folder_PDF_path, url)
    # get_pic_by_url(folder_PIC_path, listpicpath)

    #pdf转png
    file_list = []
    count = 0

    # while (True):

    def getListFiles(path):
        ret = []
        listSpicalpath = set()
        for root, dirs, files in os.walk(path):
            for filespath in files:
                ret.append(os.path.join(root, filespath))
            for i in ret:
                if os.path.splitext(i)[1] == ".pdf":
                    listSpicalpath.add(i)
        return ret

    def get_file_list(dir, file_type_list=['PDF']):
        '''获取指定文件夹下指定类型文件路径
        :param
        dir: 文件夹路径
        :param
        file_type_list: 文件类型
        :param
        file_list: 文件列表'''
        for root, _, files in os.walk(dir):
            for file in files:
                file_type = file[file.rfind('.') + 1:]
            if file_type in file_type_list:
                file_list.append(os.path.join(root, file))
            return file_list

    # def get_file_name(path_string):
    #     '''获取文件名称，不含后缀""'''
    #     pattern = re.compile(r'([^<>/\|:""*?]+).\w+$')
    #     data = pattern.findall(path_string)
    #     if data:
    #         return data[0]

    def pyMuPDF_fitz(file_dir_path, out_file_path, file_type_list=['pdf']):
        if not os.path.exists(out_file_path):  # 判断输出文件夹是否存在
            os.makedirs(out_file_path)  # 若不存在就创建
            print("imagePath=" + out_file_path)
        file_paths = getListFiles(file_dir_path)  # 获取文件列表

        n = 0
        t = 0
        index = 0
        for file in file_paths:
            n = n + 1
            pdfDoc = fitz.open(file)
            # print("convert File=" + file)
            m = 0
            for pg in range(pdfDoc.pageCount):
                index += 1
                page = pdfDoc[pg]
                rotate = int(0)

                # 每个尺寸的缩放系数为1.3，这将为我们生成分辨率提高2.6的图像。
                # 此处若是不做设置，默认图片大小为：792X612, dpi=72
                zoom = int(1000)  # 这里改为1000
                # zoom_x = 2  # 1.33333333 #(1.33333333-->1056x816)   (2-->1584x1224)
                # zoom_y = 2  # 1.33333333
                mat = fitz.Matrix(zoom / 250, zoom / 250).preRotate(rotate)
                pix = page.getPixmap(matrix=mat, alpha=False)
                ret = random.randint(1, 5000)
                pix.writePNG(out_file_path + '/' + '%s_%s_%s.png' % (ret, pg, index))  # 将图片写入指定的文件夹内filename,
                m = m + 1
                t = t + 1
                # print("convert File=" + file, '第', n, '个pdf第', m, '页', '第', index, '张 finished.')
            pdfDoc.close()
            os.remove(file)

        print('共', n, '个文件已转换完成', index, '图片。')

    pdfPath = 'PDF-OCR\PDF'  # 相对路径

    out_file_path = 'PDF-OCR\PIC'

    pyMuPDF_fitz(pdfPath, out_file_path, ['pdf'])


    #开始识别
    def getListFiles(path):
        ret = []
        listSpicalpath = set()
        for root, dirs, files in os.walk(path):
            for filespath in files:
                ret.append(os.path.join(root, filespath))
            for i in ret:
                if os.path.splitext(i)[1] in ('.png', '.jpg', '.jpeg', '.gif', '.tif', '.bmp', '.webp'):
                    listSpicalpath.add(i)
        return ret

    path = 'PDF-OCR\PIC'
    error_path = 'PDF-OCR\PIC_ERROR'
    res_list = getListFiles(path)
    count = 0
    Failure_list = []

    for file in res_list:
        count += 1
        print("正在识别第", count, '个图片')

        # child ='PDF-OCR\PIC\_images_0_1.png'

        image = cv2.imread(file)

        sp = image.shape  # 获取图像形状：返回【行数值，列数值】列表
        sz1 = sp[0]  # 图像的高度（行 范围）
        sz2 = sp[1]  # 图像的宽度（列 范围)

        # 获取截图区域的信息
        '''

        '''
        # 地址信息的截图区域
        x_addr_start = int(0.0850 * sz2)  # x start
        x_addr_end = int(0.8150 * sz2)  # x end
        y_addr_start = int(0.2105 * sz1)  # y start
        y_addr_end = int(0.3135 * sz1)  # y end
        # 定义订单号的截图区域
        x_order_start = int(0.0311 * sz1)  # x start
        x_order_end = int(0.5739 * sz1)  # x end
        y_order_start = int(0.4743 * sz1)  # y start
        y_order_end = int(0.5762 * sz1)  # y end
        # 裁剪图像
        order_Img = image[y_order_start:y_order_end, x_order_start:x_order_end]
        addr_Img = image[y_addr_start:y_addr_end, x_addr_start:x_addr_end]

        # cv2.imwrite("addr_Img.jpg", addr_Img)
        cv2.imwrite("order_Img.jpg", order_Img)
        # addr_img_path = 'addr_Img.jpg'
        # order_img_path = 'order_Img.jpg'

        ocr = PaddleOCR(use_angle_cls=True, lang="ch")
        # order_result = ocr.ocr(order_Img, cls=True)
        addr_result = ocr.ocr(addr_Img, cls=True)

        addr_txts = [line[1][0] for line in addr_result]
        addr_text = "".join(addr_txts)

        gray = cv2.cvtColor(order_Img, cv2.COLOR_BGR2RGB)
        # 提取图片的数据
        texts = pyzbar.decode(gray)
        for text in texts:
            order_text = text.data.decode("utf-8")
        print(order_text)
        # order_txts = [line[1][0] for line in order_result]
        # order_text = "".join(order_txts)
        # order_text = re.sub('U', 'J', order_text)
        # print(order_text)

        # 获取顾客姓名
        Customer_name = re.sub('[0-9]', '', addr_text[0:10])
        # 获取顾客手机号
        Phone_number = str(re.findall(r"1\d{10}", addr_text)[0]).strip()
        addr_text = re.sub(Customer_name, '', addr_text)
        addr_text = re.sub(Phone_number, '', addr_text)

        url = f'https://restapi.amap.com/v3/geocode/geo?address={addr_text}&output=JSON&key=c11e133af559840d0238c74eac9bfbf0'
        res = requests.get(url)
        # 返回json格式
        result = res.json()
        # print(result)
        # 从json中匹配对应字符

        if result['geocodes'] == [] or result['geocodes'][0]['country'] == [] or result['geocodes'][0][
            'province'] == [] or \
                result['geocodes'][0]['city'] == [] or result['geocodes'][0]['district'] == []:
            Failure_list.append(order_text)
            shutil.move(file, error_path)  # 移动文件
            print("move %s -> %s" % (file, error_path))
            continue

        Country = result['geocodes'][0]['country']
        Province = result['geocodes'][0]['province']
        City = result['geocodes'][0]['city']
        District = result['geocodes'][0]['district']

        addr_details = addr_text
        final_result.append([order_text, Customer_name, Phone_number, Country, Province, City, District, addr_details])
        print(final_result)
        # 写入csv文件
        # with open('result.csv', 'a', newline='') as csvfile:
        #     writer = csv.writer(csvfile)
        #     writer.writerow([order_text, Customer_name, Phone_number, Country, Province, City, District, addr_details])
        listkey=['order_text', 'Customer_name', 'Phone_number', 'Country', 'Province', 'City', 'District', 'addr_details']
        os.remove(file)

    return json.dumps([dict(zip(listkey, item)) for item in final_result], indent=2, ensure_ascii=False)



if __name__ == '__main__':
    # app.config['JSON_AS_ASCII'] = False
    app.run(port=5001)
